const debug = require('debug')('koa-session:context');
const session = require('koa-session');
const Redis = require('./db/redis');
class ContextStore {
  constructor(redisConfig) {
    this.redis = new Redis(redisConfig).use(0);
  }

  async get(key, maxAge, options) {
    debug('获取session key:%s, maxAge:%i options:%o', key, maxAge, options);
    let data = await this.redis.get(`SESSION:${key}`);
    return JSON.parse(data);
  }

  async set(key, data, maxAge, options) {
    debug('设置session key:%s, data:%o, maxAge:%i, options:%o', key, data, maxAge, options);
    try {
      await this.redis.set(`SESSION:${key}`, JSON.stringify(data), 'EX', maxAge / 1000);
    } catch (e) { }
    return key;
  }

  async destroy(key, options) {
    debug('destroy session key:%s, options:%o', key, options);
    return await this.redis.del(`SESSION:${key}`);
  }
}
module.exports = (config, app) => {
  const sessionRedisConf = config.redis;
  if (sessionRedisConf) {
    delete config.redis;
    config.store = new ContextStore({ clients: { 0: sessionRedisConf } });
  }
  return session(config, app);
};
